package liecai_class.day09;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * NIO服务器端
 */
public class Demo09 {
    public static void main(String[] args) throws IOException {
        //1.创建ssc
        ServerSocketChannel ssc = ServerSocketChannel.open();
        //2.绑定端口
        ssc.bind(new InetSocketAddress(9999));
        //3.开启非阻塞模式 - ACCEPT CONNECT READ WRITE不再阻塞
        ssc.configureBlocking(false);
        //4.接收客户端的连接
        SocketChannel sc = null;
        while(sc == null){
            sc = ssc.accept();
        }
        sc.configureBlocking(false);
        //5.读取客户端发送的数据
        ByteBuffer buf = ByteBuffer.allocate(10);
        while(buf.hasRemaining()){
            sc.read(buf);
        }
        //6.打印客户端发来的数据
        String msg = new String(buf.array());
        System.out.println("收到数据:"+msg);

        //7.向客户端写回数据
        ByteBuffer buf2 = ByteBuffer.wrap("hello java!".getBytes());
        while(buf2.hasRemaining()){
            sc.write(buf2);
        }

        //8.关闭通道
        sc.close();
        ssc.close();
    }
}
